/**
 * @author mgw1986* @version V1.0* @date 2019-07-03 13:10
 * 自动化发布pipeline脚本，自动打包、代码风格检查、构建docker镜像、上传docker镜像、发布镜像
 */
pipeline {
    agent any
    environment {
        PROJECT_NAME = 'nhi-cloud-waste-service'
        REMOTE_DIR = '/usr/local/docker'
        IMAGE_REPOSITORY = 'registry-vpc.cn-qingdao.aliyuncs.com'
    }
    parameters {
        string(name: 'remoteUrl', defaultValue: '118.190.103.237', description: '远程服务器地址')
        choice(name: 'profile', choices: ['test','dev', 'prod'], description: '构建环境')
    }
    stages {
//        stage('静态检查') {
//            steps {
//                echo "starting codeAnalyze with SonarQube......"
//                withSonarQubeEnv('sonarqube') {
//                    sh "mvn -f pom.xml clean compile sonar:sonar -Dsonar.projectKey=${PROJECT_NAME}"
//                }
//            }
//        }
        stage('构建代码') {
            steps {
                sh("mvn clean package -P${params.profile}")
            }
        }
        stage('构建镜像') {
            steps {
                script {
                    //关闭镜像
                    def stopImages = sh(script: "docker ps -a | grep \"${PROJECT_NAME}\" | grep \"${params.profile}\" | awk '{print \$1}'", returnStdout: true).trim()
                    if (stopImages) {
                        sh("docker rm -f ${stopImages}")
                    }
                    //删除镜像
                    def delImages = sh(script: "docker images | grep \"${PROJECT_NAME}\" | grep \"${params.profile}\" | awk '{print \$3}'", returnStdout: true).trim()
                    if (delImages) {
                        sh("docker rmi ${delImages}")
                    }
                    sh 'mvn dockerfile:build -P${profile}'
                }
            }
        }
        stage('推送镜像') {
            steps {
                script {
                    withCredentials([usernamePassword(credentialsId: 'aliDocker', usernameVariable: 'username', passwordVariable: 'password')]) {
                        def imageName = sh(script: "cat target/docker/image-name", returnStdout: true).trim()
                        if (imageName.indexOf(params.profile)) {
                            sh("docker login --username=${username} -p${password} ${IMAGE_REPOSITORY}")
                            sh("docker push ${imageName}")
                        } else {
                            error "未找到镜像"
                        }
                    }
                }
            }
        }
        stage('发布镜像') {
            steps {
                script {
                    def remotePath = "${REMOTE_DIR}/${PROJECT_NAME}" as String
                    def tag = sh(script: "cat target/docker/tag", returnStdout: true).trim()
                    def remote = [:]
                    remote.name = "remote-service"
                    remote.host = params.remoteUrl
                    remote.allowAnyHosts = true
                    withCredentials([usernamePassword(credentialsId: 'epi-cloud-test', usernameVariable: 'username', passwordVariable: 'password')]) {
                        remote.user = userName
                        remote.password = password
                        //替换服务器上脚本的版本号
                        sshCommand remote: remote, command: "sed -i 's/\\(version=\\)\\(.*\\)/\\1${tag}/' ${remotePath}/start.sh"
                        //启动镜像
                        sshCommand remote: remote, command: "${remotePath}/start.sh"
                    }
                }
            }
        }
    }
    post {
        success {
            dingTalk accessToken:'05cd1abdf7d6435630b4dd07547d6db0a3da586325ae223d53cd675b45263a3a',
                    imageUrl:'http://qiniucdn.ws361.cn/dingding_success.png',
                    jenkinsUrl:"http://118.190.103.237:9010",
                    message:"医废服务测试环境构建成功",
                    notifyPeople:''
        }
        failure {
            dingTalk accessToken:'05cd1abdf7d6435630b4dd07547d6db0a3da586325ae223d53cd675b45263a3a',
                    imageUrl:'http://qiniucdn.ws361.cn/dingding_faild.png',
                    jenkinsUrl:'http://118.190.103.237:9010',
                    message:"医废服务测试环境构建失败",
                    notifyPeople:''
        }
        //构造完成清空目录
        always {
            deleteDir()
        }
    }
}